package top.tomxwd.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author xieweidu
 * @createDate 2020-08-18 23:23
 */
@Component
public class GatewayFilter implements GlobalFilter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(GatewayFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("*************************** 自定义全局过滤器GatewayFilter ***************************");
        String username = exchange.getRequest().getQueryParams().getFirst("username");
        if (username == null || "".equals(username)) {
            logger.info("username为空，非法用户访问");
            // 改个不接收该请求的状态码 打回去
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        // 通过验证
        logger.info("username为：{}", username);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        // 越小 优先级越高
        return 0;
    }
}
